package com.atguigu.bigdata.spark.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

public class JDBCUtil_JAVA {
    private DataSource dataSource;
    public JDBCUtil_JAVA() throws Exception {
        Properties properties = new Properties();
        properties.setProperty("driverClassName", "com.mysql.jdbc.Driver");
        properties.setProperty("url", "jdbc:mysql://127.0.0.1:3306/spark-streaming?useUnicode=true&characterEncoding=UTF-8");
        properties.setProperty("username", "root");
        properties.setProperty("password", "123123");
        properties.setProperty("maxActive", "50");
        dataSource = DruidDataSourceFactory.createDataSource(properties);
    }

    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
    //执行SQL语句,单条数据插入
    public int executeUpdate(Connection connection, String sql, List<Object> params) {
        int rnt = 0;
        PreparedStatement pstmt = null;
        try{
            connection.setAutoCommit(false);
            pstmt = connection.prepareStatement(sql);
            if(params != null && params.size() > 0) {
                for(int i = 0; i < params.size(); i++) {
                    pstmt.setObject(i + 1, params.get(i));
                }
            }
            rnt = pstmt.executeUpdate();
            connection.commit();
            pstmt.close();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return rnt;
    }

    public boolean isExist(Connection connection,String sql, List<Object> params) {
        boolean flag = false;
        PreparedStatement pstmt = null;
        try{
            pstmt = connection.prepareStatement(sql);
            for(int i = 0; i < params.size(); i++) {
                pstmt.setObject(i + 1, params.get(i));
            }
            flag = pstmt.executeQuery().next();
            pstmt.close();
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
        return flag;
    }

}
